package cn.jji8.patternLogin.bungeeCord;

import cn.jja8.knapsackToGo3.allUsed.Communication;
import cn.jja8.knapsackToGo3.bungeeCord.KnapsackToGo3Bc;
import cn.jja8.patronSaint_2021_7_8_2056.allUsed.file.ReadFile;
import cn.jja8.patronSaint_2021_7_8_2056.allUsed.file.YamlConfig;
import net.md_5.bungee.api.ChatMessageType;
import net.md_5.bungee.api.chat.TextComponent;
import net.md_5.bungee.api.config.ServerInfo;
import net.md_5.bungee.api.connection.ProxiedPlayer;
import net.md_5.bungee.api.connection.Server;
import net.md_5.bungee.api.event.*;
import net.md_5.bungee.api.plugin.Listener;
import net.md_5.bungee.api.plugin.Plugin;
import net.md_5.bungee.event.EventHandler;

import java.io.File;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.util.*;


@SuppressWarnings("unused")
public class PatternLogin extends Plugin implements Listener {
    Config config = new Config();

    public Config get配置() {
        return config;
    }

    //未登录的玩家列表
    final Set<String> PlayerSet = new HashSet<>();


    @Override
    public void onLoad() {
        getLogger().info("加载配置文件！");
        File 配置文件 = new File(getDataFolder(),"配置.yml");
        if (配置文件.exists()){
            try {
                config = YamlConfig.读取配置(ReadFile.读取为字符串(配置文件),Config.class);
            } catch (IOException e) {
                e.printStackTrace();
                getLogger().severe("配置文件读取失败！");
                try { Thread.sleep(10000); } catch (InterruptedException ignored) { }
                getProxy().stop();
            }
        }else {
            try {
                ReadFile.写入字符串(YamlConfig.保存配置(config),配置文件);
            } catch (IOException e) {
                e.printStackTrace();
                getLogger().severe("释放配置文件失败！");
            }
        }
    }

    @Override
    public void onEnable() {
        getLogger().info("开始加载！");
        Plugin plugin = getProxy().getPluginManager().getPlugin("KnapsackToGo");
        if (plugin==null){
            getLogger().severe("需要KnapsackToGo3作为前置！！！");
            try { Thread.sleep(10000); } catch (InterruptedException ignored) { }
            getProxy().stop();
        }
        KnapsackToGo3Bc.get通信().注册不回馈命令接收器("patternLogin", this::玩家已登录);
        KnapsackToGo3Bc.get通信().注册回馈命令接收器("patternLogin",this::获取登录消息);
        getProxy().getPluginManager().registerListener(this,this);
        getLogger().info("加载完成！");
    }

    private byte[] 获取登录消息(Communication communication, String s, byte[] bytes) {
        String playerName = new String(bytes);
        boolean b = !PlayerSet.contains(playerName);
        System.out.println("将玩家"+playerName+"的登录情况"+b+"发送给登录服务器。");
        return String.valueOf(b).getBytes(StandardCharsets.UTF_8);
    }

    private void 玩家已登录 (Communication communication, String s, byte[] bytes) {
        String playerName = new String(bytes, StandardCharsets.UTF_8);
        boolean 没有登录 = PlayerSet.remove(playerName);
        if (没有登录){
            if (get配置().登录后跳转上次离开时服务器){
                //将玩家传送到上次下线时的服务器
                getProxy().getScheduler().runAsync(this, () -> {
                    String serverName = new String(KnapsackToGo3Bc.get数据().获取数据("OfflineServer/"+playerName),StandardCharsets.UTF_8);
                    ProxiedPlayer player = getProxy().getPlayer(playerName);
                    ServerInfo setve = getProxy().getServerInfo(serverName);
                    if (player!=null&setve!=null){
                        player.connect(setve);
                    }
                });
            }
        }
    }
    @EventHandler
    public void onPostLogin(LoginEvent event) {//玩家进入时
        PlayerSet.add(event.getConnection().getName());
    }
    @EventHandler
    public void PlayerDisconnectEvent(PlayerDisconnectEvent e){//玩家离开时
        String playerName = e.getPlayer().getName();
        if (!PlayerSet.remove(playerName)){
            KnapsackToGo3Bc.get数据().写入数据("OfflineServer/"+playerName,e.getPlayer().getServer().getInfo().getName().getBytes(StandardCharsets.UTF_8));
        }
    }
    /**
     * 服务器连接事件
     * */
    @EventHandler
    public void 服务器连接(ServerConnectEvent event){
        Server server = event.getPlayer().getServer();
        if (server==null){
            return;
        }
        if (get配置().防止未登录玩家切换服务器){
            if (PlayerSet.contains(event.getPlayer().getName())){
                event.setCancelled(true);
                event.getPlayer().sendMessage(ChatMessageType.CHAT,new TextComponent("登录之前禁止跳转服务器！"));
            }
        }
    }
}
